/* 
 * Copyright 2005-2010 Samuel Mello & Eduardo Schnell
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; version 2 or later of the License.
 * 
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 * 
 */

/*
 * SongsSearchPanel.java
 *
 * Created on 22 de Dezembro de 2005, 21:32
 */

package datasoul.serviceitems.song;

import java.io.File;

import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.RowFilter;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import datasoul.servicelist.ServiceListTable;
import datasoul.util.ObjectManager;

/**
 *
 * @author  Administrador
 */
public class SongsSearchPanel extends javax.swing.JPanel implements javax.swing.event.TableModelListener{

    /**
	 * 
	 */
	private static final long serialVersionUID = -8178849318898277849L;
	private AllSongsListTable allSongsListTable;
    private int songColumn;
    private TableRowSorter<TableModel> sorter;
    /**
     * Creates new form SongsSearchPanel
     */
    public SongsSearchPanel() {
        initComponents();

        tableSongList.setDroppable(false);
        
        allSongsListTable = AllSongsListTable.getInstance();

        tableSongList.setModel(allSongsListTable);

        songColumn = allSongsListTable.getSongColumn();

        tableSongList.setShowVerticalLines(false);
        
        TableColumn col1 = tableSongList.getColumnModel().getColumn(0);
        col1.setMaxWidth(30);
        col1.setMinWidth(30);

        tableSongList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        sorter = new TableRowSorter<TableModel>(allSongsListTable);
        tableSongList.setRowSorter(sorter);

        tableSongList.getSelectionModel().addListSelectionListener(new SongSearchPanelSelectionListener() );

    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        toolBar = new javax.swing.JToolBar();
        btnNew = new javax.swing.JButton();
        btnEdit = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnAdd = new javax.swing.JButton();
        labelString = new javax.swing.JLabel();
        fieldString = new javax.swing.JTextField();
        scroolSongList = new javax.swing.JScrollPane();
        tableSongList = new datasoul.util.DnDTable();

        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });

        toolBar.setBorder(null);
        toolBar.setFloatable(false);
        toolBar.setMinimumSize(new java.awt.Dimension(150, 32));
        toolBar.setOpaque(false);

        btnNew.setIcon(new javax.swing.ImageIcon(getClass().getResource("/datasoul/icons/v2/document-new.png"))); // NOI18N
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("datasoul/internationalize"); // NOI18N
        btnNew.setText(bundle.getString("NEW")); // NOI18N
        btnNew.setToolTipText(bundle.getString("CREATE A NEW SONG")); // NOI18N
        btnNew.setBorderPainted(false);
        btnNew.setFocusPainted(false);
        btnNew.setFocusable(false);
        btnNew.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnNewMouseClicked(evt);
            }
        });
        toolBar.add(btnNew);

        btnEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/datasoul/icons/v2/gtk-edit.png"))); // NOI18N
        btnEdit.setText(bundle.getString("EDIT")); // NOI18N
        btnEdit.setToolTipText(bundle.getString("EDIT SONG")); // NOI18N
        btnEdit.setBorderPainted(false);
        btnEdit.setFocusPainted(false);
        btnEdit.setFocusable(false);
        btnEdit.setName(""); // NOI18N
        btnEdit.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnEditMouseClicked(evt);
            }
        });
        btnEdit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditActionPerformed(evt);
            }
        });
        toolBar.add(btnEdit);

        btnDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/datasoul/icons/v2/edit-delete.png"))); // NOI18N
        btnDelete.setText(bundle.getString("DELETE")); // NOI18N
        btnDelete.setToolTipText(bundle.getString("DELETE SONG")); // NOI18N
        btnDelete.setBorderPainted(false);
        btnDelete.setFocusPainted(false);
        btnDelete.setFocusable(false);
        btnDelete.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnDeletebtnRemoveMouseClicked(evt);
            }
        });
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });
        toolBar.add(btnDelete);

        btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/datasoul/icons/v2/list-add.png"))); // NOI18N
        btnAdd.setText(bundle.getString("ADD")); // NOI18N
        btnAdd.setToolTipText(bundle.getString("ADD SELECTED SONG TO SERVICE")); // NOI18N
        btnAdd.setBorderPainted(false);
        btnAdd.setFocusable(false);
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });
        toolBar.add(btnAdd);

        labelString.setIcon(new javax.swing.ImageIcon(getClass().getResource("/datasoul/icons/v2/stock_zoom-object.png"))); // NOI18N
        labelString.setText(bundle.getString("SEARCH")); // NOI18N
        labelString.setFocusable(false);
        labelString.setInheritsPopupMenu(false);
        toolBar.add(labelString);

        fieldString.setColumns(15);
        fieldString.setMaximumSize(new java.awt.Dimension(2147483647, 20));
        fieldString.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fieldStringActionPerformed(evt);
            }
        });
        fieldString.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                fieldStringKeyTyped(evt);
            }
            public void keyPressed(java.awt.event.KeyEvent evt) {
                fieldStringKeyPressed(evt);
            }
        });
        toolBar.add(fieldString);

        tableSongList.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tableSongList.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableSongListMouseClicked(evt);
            }
        });
        tableSongList.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tableSongListKeyPressed(evt);
            }
        });
        scroolSongList.setViewportView(tableSongList);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(scroolSongList, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE)
            .addComponent(toolBar, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(toolBar, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(scroolSongList, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnNewMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnNewMouseClicked
        SongEditorForm songEditor = new SongEditorForm();
        
        songEditor.setVisible(true);
    }//GEN-LAST:event_btnNewMouseClicked

    private void btnEditMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnEditMouseClicked

    }//GEN-LAST:event_btnEditMouseClicked

    private void btnDeletebtnRemoveMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnDeletebtnRemoveMouseClicked

    }//GEN-LAST:event_btnDeletebtnRemoveMouseClicked

    private void tableSongListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableSongListMouseClicked

        if (evt.getClickCount() > 1){
            btnEditActionPerformed(null);
        }

    }//GEN-LAST:event_tableSongListMouseClicked

    private void tableSongListKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tableSongListKeyPressed
    }//GEN-LAST:event_tableSongListKeyPressed

    private void showItem(){

        if (tableSongList.getSelectedRow() != -1){
            int idx = sorter.convertRowIndexToModel(tableSongList.getSelectedRow());
            if (ObjectManager.getInstance().getDatasoulMainForm() != null){
                ObjectManager.getInstance().getDatasoulMainForm().viewSong((Song)tableSongList.getModel().getValueAt(idx,songColumn));
            }
        }

    }    
    
    private void fieldStringKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_fieldStringKeyPressed

        SwingUtilities.invokeLater( new Runnable(){

            public void run(){
                final String searchStr = fieldString.getText().toUpperCase();
                if (searchStr.length() > 0){
                    RowFilter<Object, Object> filter = new RowFilter<Object, Object>() {

                        public boolean include(Entry<?,?> entry) {

                            String item = ((Song) entry.getValue(songColumn)).getSearchText();
                            if (item.contains(searchStr)) {
                                return true;
                            } else {
                                return false;
                            }
                        }
                    };
                    sorter.setRowFilter(filter);
                }else{
                    sorter.setRowFilter(null);
                }

            }

        });
       
    }//GEN-LAST:event_fieldStringKeyPressed




    private void fieldStringActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fieldStringActionPerformed
        
    }//GEN-LAST:event_fieldStringActionPerformed

    private void fieldStringKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_fieldStringKeyTyped

    }//GEN-LAST:event_fieldStringKeyTyped

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized

    }//GEN-LAST:event_formComponentResized

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        if (tableSongList.getSelectedRow() >= 0){
            int idx = sorter.convertRowIndexToModel(tableSongList.getSelectedRow());

            Song song = (Song)tableSongList.getModel().getValueAt(idx,songColumn);
            String filePath = song.getFilePath();

            File file = new File(filePath);
            if(JOptionPane.showConfirmDialog(this,java.util.ResourceBundle.getBundle("datasoul/internationalize").getString("ARE YOU SURE TO DELETE")+" "+song.getTitle()+"?" ,java.util.ResourceBundle.getBundle("datasoul/internationalize").getString("CONFIRM"),JOptionPane.YES_NO_OPTION)==JOptionPane.YES_OPTION){
                if(file.delete()){
                    tableSongList.removeItem();
                }
            }
            this.repaint();
        }
    }//GEN-LAST:event_btnDeleteActionPerformed

    private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
        if (tableSongList.getSelectedRow() >= 0){
            int idx = sorter.convertRowIndexToModel(tableSongList.getSelectedRow());
            ((Song)tableSongList.getModel().getValueAt(idx,songColumn)).edit();
        }
    }//GEN-LAST:event_btnEditActionPerformed

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        if (tableSongList.getSelectedRow() >= 0){
            int idx = sorter.convertRowIndexToModel(tableSongList.getSelectedRow());
            ServiceListTable.getActiveInstance().addItem(tableSongList.getModel().getValueAt(idx,songColumn));
        }
    }//GEN-LAST:event_btnAddActionPerformed

    public void tableChanged(TableModelEvent e) {
        this.repaint();
    }

    public void requestFocusForSearch(){
        fieldString.requestFocus();
    }


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnNew;
    private javax.swing.JTextField fieldString;
    private javax.swing.JLabel labelString;
    private javax.swing.JScrollPane scroolSongList;
    private datasoul.util.DnDTable tableSongList;
    private javax.swing.JToolBar toolBar;
    // End of variables declaration//GEN-END:variables

    public class SongSearchPanelSelectionListener implements ListSelectionListener {

        public void valueChanged(ListSelectionEvent e) {
            showItem();
        }
        
    }

}


